#include "mqtt_client_builder.h"

#include <chrono>
#include <cstring>
#include <iostream>
#include <string>
#include <thread>

void subscriber()
{
    MQTTClientBuilder builder;
    builder.set_server_uri("tcp://127.0.0.1:1883").set_client_id("ExampleClientSub").set_connect_timeout_s(10);

    auto client = builder.build();
    if (!client->connect()) {
        std::cout << "client connect failed." << std::endl;
        return;
    }
    std::cout << "client connect succeed." << std::endl;

    std::string topic = "test_message";
    int         qos   = 0;
    client->subscribe(topic, qos);

    int ch;
    do {
        std::cout << "Press Q<Enter> to quit: ";
        ch = getchar();
    } while (ch != 'Q' && ch != 'q');

    std::cout << std::endl;
    client->unsubscribe(topic);
    client->disconnect();
    std::cout << "client disconnected." << std::endl;
}

void publisher()
{
    MQTTClientBuilder builder;
    builder.set_server_uri("tcp://127.0.0.1:1883").set_client_id("ExampleClientPub").set_connect_timeout_s(10);

    auto client = builder.build();
    if (!client->connect()) {
        std::cout << "client connect failed." << std::endl;
        return;
    }

    std::cout << "client connect succeed." << std::endl;

    std::string topic = "test_message";
    std::string message;
    int         qos   = 0;
    int         msgId = 0;

    int ch;
    do {
        ch = getchar();
        if (ch == 'Q' || ch == 'q')
            break;

        message = "Hello, world: " + std::to_string(++msgId);
        if (client->publish(topic, message, qos)) {
            std::cout << "publish msg: " << message << std::endl;
        }
        std::this_thread::sleep_for(std::chrono::milliseconds(100));
    } while (true);

    client->disconnect();
    std::cout << "client disconnected." << std::endl;
}

int main(int argc, char *argv[])
{
    if (argc < 2) {
        std::cout << "Usage: " << argv[0] << " sub/pub" << std::endl;
        return 0;
    }

    if (strcmp(argv[1], "sub") == 0) {
        subscriber();
    } else if (strcmp(argv[1], "pub") == 0) {
        publisher();
    } else {
        std::cout << "Usage: " << argv[0] << " sub/pub" << std::endl;
    }
    return 0;
}
